﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimplexEngine
{
    public class VertexAnimationFrame : AnimationKeyFrame
    {        
        public Dictionary<String, Vertex[]> MeshParts { get { return mesh_parts; } }
        protected Dictionary<String, Vertex[]> mesh_parts = new Dictionary<String, Vertex[]>();
    }

    public class VertexAnimation : Animation
    {
        protected List<AnimationKeyFrame> frames = new List<AnimationKeyFrame>();
        public List<AnimationKeyFrame> Frames { get { return frames; } }

        public override void UpdateMeshBuffer(float time, AnimationMeshInstance mesh_instance, ref Dictionary<String, MeshBuffer> mesh_buffers) 
        {
            AnimationKeyFrame frame1 = null;
            AnimationKeyFrame frame2 = null;
            float delta = 0.0f;

            GetDeltaAndFrame(time, out delta, frames, out frame1, out frame2);

            if (frame1 == null || frame2 == null)
                return;

            foreach (KeyValuePair<String, MeshBuffer> mesh_buffer in mesh_buffers)
            {
                Vertex[] vertices = mesh_buffer.Value.GetVertices();
                Vertex[] part1_vertices = ((VertexAnimationFrame)frame1).MeshParts[mesh_buffer.Key];
                Vertex[] part2_vertices = ((VertexAnimationFrame)frame2).MeshParts[mesh_buffer.Key];

                for (int i = 0; i < mesh_buffer.Value.GetVertexCount(); ++i)
                {
                    vertices[i].Position = part1_vertices[i].Position + (part2_vertices[i].Position - part1_vertices[i].Position) * delta;
                    vertices[i].Normal = part1_vertices[i].Normal + (part2_vertices[i].Normal - part1_vertices[i].Normal) * delta;
                }                
            }
        }

        public override float Length
        {
            get
            {
                if (frames.Count > 0)
                    return frames.Last().Time;
                return base.Length;
            }
        }
    }
}
